package com.damonclient.complexClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.util.Scanner;

/**
 * Netty客户端启动类
 */
public class NettyClient {

    public static String host = "127.0.0.1";  //服务端ip地址
    public static int port = 8888;//远程服务端端口
    //线程池
    private static EventLoopGroup group = new NioEventLoopGroup();
    private static  Bootstrap bootstrap = new Bootstrap();
    private static Channel channel;

    public static void main(String[] args) throws InterruptedException, IOException {
        System.out.println("客户端成功启动...");
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new NettyClientInitializer());
        //异步连接服务端
        channel = bootstrap.connect(host, port).sync().channel();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容...");
        //这里设置一个死循环，这样就可以持续发送消息，否则客户端在运行一次后就结束运行。
        while (true) {
            String message = scanner.nextLine();
            send(message);
            if ("quit".equalsIgnoreCase(message)) {
                channel.closeFuture().sync();
                group.shutdownGracefully();
            }
        }
    }

    public static void send(String str) throws IOException{
//        String str="Hello Netty";
        channel.writeAndFlush(str+ "\r\n");
        System.out.println("客户端发送数据:"+str);
    }

}

